package com.lorenzogao.pley.common.util


import android.Manifest
import android.accounts.AccountManager
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.content.Context
import android.content.pm.PackageManager
import android.net.Uri
import android.net.wifi.WifiManager
import android.os.Build
import android.provider.Settings
import android.telephony.TelephonyManager
import android.util.DisplayMetrics
import android.view.WindowManager
import java.net.NetworkInterface
import java.net.SocketException
import java.util.*

/**
 *
 *
 * @author Ivan
 * @version V1.0
 * @Package com.cniao5.cniao5play.common.util
 * @Description: ${TODO}(用一句话描述该文件做什么)
 * @date
 */

object DeviceUtils {

    val gprsip: String?
        get() {
            var ip: String? = null
            try {
                val en = NetworkInterface.getNetworkInterfaces()
                while (en.hasMoreElements()) {
                    val enumIpAddr = en.nextElement().inetAddresses
                    while (enumIpAddr.hasMoreElements()) {
                        val inetAddress = enumIpAddr.nextElement()
                        if (!inetAddress.isLoopbackAddress) {
                            ip = inetAddress.hostAddress
                        }
                    }
                }
            } catch (e: SocketException) {
                e.printStackTrace()
                ip = null
            }

            return ip
        }


    val serial: String
        get() = Build.SERIAL


    val model: String
        get() = Build.MODEL

    val buildBrand: String
        get() = Build.BRAND

    val buildHost: String
        get() = Build.HOST

    val buildTags: String
        get() = Build.TAGS

    val buildTime: Long
        get() = Build.TIME

    val buildUser: String
        get() = Build.USER

    val buildVersionRelease: String
        get() = Build.VERSION.RELEASE

    val buildVersionCodename: String
        get() = Build.VERSION.CODENAME

    val buildVersionIncremental: String
        get() = Build.VERSION.INCREMENTAL

    val buildVersionSDK: Int
        get() = Build.VERSION.SDK_INT

    val buildID: String
        get() = Build.ID

    val supportedABIS: Array<String>
        get() {
            var result: Array<String>? = arrayOf("-")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                result = Build.SUPPORTED_ABIS
            }
            if (result == null || result.size == 0) {
                result = arrayOf("-")
            }
            return result
        }

    val manufacturer: String
        get() = Build.MANUFACTURER


    val bootloader: String
        get() = Build.BOOTLOADER

    val displayVersion: String
        get() = Build.DISPLAY


    val language: String
        get() = Locale.getDefault().language

    val osVersion: String
        get() = Build.VERSION.RELEASE

    val psuedoUniqueID: String
        get() {
            var devIDShort = "35" + Build.BOARD.length % 10 + Build.BRAND.length % 10
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                devIDShort += Build.SUPPORTED_ABIS[0].length % 10
            } else {
                devIDShort += Build.CPU_ABI.length % 10
            }
            devIDShort += Build.DEVICE.length % 10 + Build.MANUFACTURER.length % 10 + Build.MODEL.length % 10 + Build.PRODUCT.length % 10
            var serial: String
            try {
                serial = Build::class.java.getField("SERIAL").get(null).toString()
                return UUID(devIDShort.hashCode().toLong(), serial.hashCode().toLong()).toString()
            } catch (e: Exception) {
                serial = "ESYDV000"
            }

            return UUID(devIDShort.hashCode().toLong(), serial.hashCode().toLong()).toString()
        }

    val fingerprint: String
        get() = Build.FINGERPRINT

    val hardware: String
        get() = Build.HARDWARE

    val product: String
        get() = Build.PRODUCT

    val device: String
        get() = Build.DEVICE

    val board: String
        get() = Build.BOARD

    val radioVersion: String
        get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) Build.getRadioVersion() else ""


    fun getAndroidID(ctx: Context): String {
        return Settings.Secure.getString(ctx.contentResolver, Settings.Secure.ANDROID_ID)
    }

    @SuppressLint("MissingPermission")
    fun getIMEI(ctx: Context): String {
        return (ctx.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager).deviceId
    }

    @SuppressLint("MissingPermission")
    fun getIMSI(ctx: Context): String? {
        val tm = ctx.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        return if (tm.subscriberId != null) tm.subscriberId else null
    }

    @SuppressLint("MissingPermission")
    fun getWifiMacAddr(ctx: Context): String? {
        var macAddr: String? = ""
        try {
            val wifi = ctx.getSystemService(Context.WIFI_SERVICE) as WifiManager
            macAddr = wifi.connectionInfo.macAddress
            if (macAddr == null) {
                macAddr = ""
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return macAddr
    }

    fun getIP(ctx: Context): String? {
        val wifiManager = ctx.getSystemService(Context.WIFI_SERVICE) as WifiManager
        return if (wifiManager.isWifiEnabled) getWifiIP(wifiManager) else gprsip
    }

    @SuppressLint("MissingPermission")
    fun getWifiIP(wifiManager: WifiManager): String {
        val wifiInfo = wifiManager.connectionInfo
        val ip = intToIp(wifiInfo.ipAddress)
        return ip ?: ""
    }

    private fun intToIp(i: Int): String {
        return (i and 0xFF).toString() + "." + (i shr 8 and 0xFF) + "." + (i shr 16 and 0xFF) + "." + (i shr 24 and 0xFF)
    }

    @SuppressLint("MissingPermission")
    fun getSIMSerial(ctx: Context): String {
        val tm = ctx.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        return tm.simSerialNumber
    }

    fun getMNC(ctx: Context): String? {
        var providersName: String? = ""
        val telephonyManager = ctx.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        if (telephonyManager.simState == TelephonyManager.SIM_STATE_READY) {
            providersName = telephonyManager.simOperator
            providersName = if (providersName == null) "" else providersName
        }
        return providersName
    }

    fun getCarrier(ctx: Context): String {
        val tm = ctx.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        return tm.networkOperatorName.toLowerCase(Locale.getDefault())
    }


    fun getScreenDisplayID(ctx: Context): String {
        val wm = ctx.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        return wm.defaultDisplay.displayId.toString()
    }

    fun getCountry(ctx: Context): String {
        val tm = ctx.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val locale = Locale.getDefault()
        return if (tm.simState == TelephonyManager.SIM_STATE_READY) tm.simCountryIso.toLowerCase(Locale.getDefault()) else locale.country.toLowerCase(locale)
    }

    //<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    fun getGSFID(context: Context): String? {
        val result: String
        val URI = Uri.parse("content://com.google.android.gsf.gservices")
        val ID_KEY = "android_id"
        val params = arrayOf(ID_KEY)
        val c = context.contentResolver.query(URI, null, null, params, null)
        if (c == null || !c.moveToFirst() || c.columnCount < 2) {
            return null
        } else {
            result = java.lang.Long.toHexString(java.lang.Long.parseLong(c.getString(1)))
        }
        c.close()
        return result
    }

    @SuppressLint("MissingPermission")
//<uses-permission android:name="android.permission.BLUETOOTH"/>
    fun getBluetoothMAC(context: Context): String? {
        var result: String? = null
        try {
            if (context.checkCallingOrSelfPermission(Manifest.permission.BLUETOOTH) == PackageManager.PERMISSION_GRANTED) {
                val bta = BluetoothAdapter.getDefaultAdapter()
                result = bta.address
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return result
    }

//    fun getUA(ctx: Context): String {
//        val system_ua = System.getProperty("http.agent")
//        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
//            WebView(ctx).settings.getDefaultUserAgent(ctx) + "__" + system_ua
//        } else {
//            WebView(ctx).settings.userAgentString + "__" + system_ua
//        }
//    }

    fun getDensity(ctx: Context): String? {
        var densityStr: String? = null
        val density = ctx.resources.displayMetrics.densityDpi
        when (density) {
            DisplayMetrics.DENSITY_LOW -> densityStr = "LDPI"
            DisplayMetrics.DENSITY_MEDIUM -> densityStr = "MDPI"
            DisplayMetrics.DENSITY_TV -> densityStr = "TVDPI"
            DisplayMetrics.DENSITY_HIGH -> densityStr = "HDPI"
            DisplayMetrics.DENSITY_XHIGH -> densityStr = "XHDPI"
            DisplayMetrics.DENSITY_400 -> densityStr = "XMHDPI"
            DisplayMetrics.DENSITY_XXHIGH -> densityStr = "XXHDPI"
            DisplayMetrics.DENSITY_XXXHIGH -> densityStr = "XXXHDPI"
        }
        return densityStr
    }

    @SuppressLint("MissingPermission")
//<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
    fun getGoogleAccounts(ctx: Context): Array<String?>? {
        if (ctx.checkCallingOrSelfPermission(Manifest.permission.GET_ACCOUNTS) == PackageManager.PERMISSION_GRANTED) {
            val accounts = AccountManager.get(ctx).getAccountsByType("com.google")
            val result = arrayOfNulls<String>(accounts.size)
            for (i in accounts.indices) {
                result[i] = accounts[i].name
            }
            return result
        }
        return null
    }
}
